package com.larry.kafka.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @ProjectName hadoop
 * @Author larry
 * @Date 23:01 2021/12/1
 * @Description 消费者
 **/
public class KafkaConsumerDemo {
    public static void main(String[] args) {
        Properties props = new Properties();

        props.put("bootstrap.servers", "hadoop102:9092");

        props.put("group.id", "test");

        //自动提交
        props.put("enable.auto.commit", "true");

        props.put("auto.commit.interval.ms", "1000");

        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

        List<String> list = new ArrayList<>();
        list.add("first");
        list.add("second");
        consumer.subscribe(list);

        //持续消费
        while (true){
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(2));
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.topic() + " : " + record.partition() + " : " + record.key() + " : " + record.value());
            }
        }

        //关闭
    }
}
